import datetime
import uuid

from api import models
from api.extension import return_code
from api.serializers.account import RegisterSerializer, AuthSerializer
from django.db.models import Q
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet


class RegisterView(CreateModelMixin, GenericViewSet):
    """ 用户注册 """
    authentication_classes = []
    serializer_class = RegisterSerializer

    def perform_create(self, serializer):
        serializer.validated_data.pop('confirm_password')
        super().perform_create(serializer)


class AuthView(APIView):
    """ 用户登录 """
    authentication_classes = []

    def post(self, request):
        # 获取用户请求，校验用户信息
        serializer = AuthSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({
                'code': return_code.VALIDATE_ERROR,
                'error': '数据校验失败',
                'detail': serializer.errors
            })

        username = serializer.validated_data.get('username')
        phone = serializer.validated_data.get('phone')
        password = serializer.validated_data.get('password')

        # 数据库校验账号合法性
        user_obj = models.UserInfo.objects.filter(Q(username=username) | Q(phone=phone), password=password).first()
        if not user_obj:
            return Response({
                'code': return_code.AUTH_FAILED,
                'error': '用户名或密码错误',
            })

        # 设置token，刷新数据库，返回用户信息
        token = str(uuid.uuid4())
        user_obj.token = token
        user_obj.token_expiry_date = datetime.datetime.now() + datetime.timedelta(weeks=2)
        user_obj.save()
        return Response({
            'code': return_code.SUCCESS,
            'data': {
                'token': token,
                'name': user_obj.username
            }
        })
